package com.silverhaze.diamond.client.ui.table.model;

import com.silverhaze.diamond.common.entity.Customer;
import com.silverhaze.diamond.common.entity.Service;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.client.ui.UIStringConstants;
import com.silverhaze.commons.db.datasource.DataSourceAction;
import com.silverhaze.commons.db.datasource.DataSourceListener;
import com.silverhaze.diamond.client.utils.db.ServiceDataSource;

import java.util.List;

/**
 * © Ivan Babanin (14.07.2007 2:43:40)
 * Project Galaxy. This part of code is strictly confidential.
 */
public class CustomersTableModel extends AbstractServiceTableModel<Customer> {
    private List<Customer> dataList;
    private static final int colCount = 3;

    public static final int ID = 0;

    public CustomersTableModel() {
        fillData(DAOLocator.getInstance().getCustomers());
        ServiceDataSource.getInstance().addDataSourceListener(new DataSourceListener<Service>() {
            public void valuesUpdated(Class<Service> clazz, List<Service> values, DataSourceAction action) {
                if (clazz.equals(Customer.class)) {
                    refreshModelAll();
                }
            }
        });
    }

    public void createFields() {
        setColCountSize(colCount);
        setColumnName(new String[]{
                UIStringConstants.NAME,
                UIStringConstants.PHONE,
                UIStringConstants.ADDRESS});
    }

    public void fillData(List data) {
        int i = 0;

        this.dataList = data;
        setData(new Object[data.size()][colCount]);

        for (Object o : data) {
            Customer c = (Customer) o;

            getData()[i][0] = c.getExtendedName();
            getData()[i][1] = c.getPhone();
            getData()[i][2] = c.getAddress();
            i++;
        }

        setRowCountSize(i);
    }

    public Customer getObjectAtRow(int row) {
        assert row >= 0 && row < dataList.size();
        return dataList.get(row);
    }

    public void refreshModelAll() {
        fillData(DAOLocator.getInstance().getCustomers());
        refreshModel();
    }
}

